<template>
  <div :style="{height:'100vh',overflowX:'hidden'}" class="index">
    <v-header :items="items"></v-header>
    <Breadcrumb :home="bread.home" :model="bread.items"/>
    <Splitter class="p-mt-5 p-mb-5" style="height: 400px">
      <SplitterPanel class="p-d-flex p-ai-center p-jc-center">
        <Chart :data="c3" :height="300" type="pie"/>
      </SplitterPanel>
      <SplitterPanel class="p-d-flex p-ai-center p-jc-center">
        <Chart :data="c4" :height="300" :width="500" type="line"/>
      </SplitterPanel>
      <SplitterPanel class="p-ai-center p-jc-center">
        <div class="content">
          <div class="inner">
            <Tag class="p-mr-2" severity="info" value="创建人"></Tag>
            <span>{{ detail.createBy }}</span>
          </div>
          <div class="inner">
            <Tag class="p-mr-2" severity="info" value="创建时间"></Tag>
            <span>{{ detail.createTime }}</span>
          </div>
          <div class="inner">
            <Tag class="p-mr-2" severity="info" value="产地"></Tag>
            <span>{{ detail.location }}</span>
          </div>
          <div class="inner">
            <Tag class="p-mr-2" severity="info" value="最大上限"></Tag>
            <span>{{ detail.upperLimit }}</span>
          </div>
          <div class="inner">
            <Tag class="p-mr-2" severity="info" value="最小下限"></Tag>
            <span>{{ detail.lowerLimit }}</span>
          </div>
          <div class="inner">
            <Tag class="p-mr-2" severity="info" value="保质期"></Tag>
            <span>{{ detail.shelfLife }}</span>
          </div>
          <div class="inner">
            <img :src="detail.pic" class="left">
            <div class="desc">
              {{ detail.info }}
            </div>
          </div>
        </div>


      </SplitterPanel>
    </Splitter>
    <Splitter>
      <SplitterPanel class="p-ai-center p-p-3 p-jc-center">
        <Tag class="p-mr-2" icon="pi pi-check" severity="success" value="未过期批次"></Tag>
        <div class="p-grid p-mt-3">
          <div v-for="item in goodsList1 " class="goods p-col-4">
            <Checkbox v-model="selectGoods" :style="{verticalAlign:'middle',marginRight:'20px'}" :value="item.id"
                      name="goods"/>
            <Tag :value="'商品编号：'+item.id" class="p-mr-2" severity="success"></Tag>
            <Tag :value="'商品价格：'+item.originPrice" class="p-mr-2" severity="info"></Tag>
          </div>
        </div>
      </SplitterPanel>
      <SplitterPanel class="p-ai-center p-p-3 p-jc-center">
        <Tag class="p-mr-2" icon="pi pi-info-circle" severity="info" value="过期批次"></Tag>
        <div class="p-grid p-mt-3">
          <div v-for="item in goodsList2" class="goods p-col-4">
            <Checkbox v-model="selectGoods" :style="{verticalAlign:'middle',marginRight:'20px'}" :value="item.id"
                      name="goods"/>
            <Tag :value="'商品编号：'+item.id" class="p-mr-2" severity="success"></Tag>
            <Tag :value="'商品价格：'+item.originPrice" class="p-mr-2" severity="info"></Tag>
          </div>
        </div>
      </SplitterPanel>
    </Splitter>
    <ScrollTop :threshold="100" class="custom-scrolltop" icon="pi pi-arrow-up" target="parent"/>
  </div>

  <Dialog :closable="false" :style="{width: '50vw'}" :visible="dialog.showInfoUpdate" header="修改商品信息">
    <div class="row">
      <div class="p-inputgroup">
      <span class="p-float-label">
        <InputText id="name" v-model="goods.commodityName"/>
          <label for="name">商品名称</label>
        </span>
      </div>
    </div>
    <div class="row">
      <div class="p-inputgroup">
        <span class="p-float-label">
          <InputText id="info" v-model="goods.info"/>
          <label for="info">商品描述</label>
        </span>
      </div>
    </div>
    <div class="row">
      <div class="p-inputgroup">
      <span class="p-float-label">
        <InputNumber id="max" v-model="goods.upperLimit"/>
          <label for="max">商品最大上限</label>
        </span>
      </div>
    </div>
    <div class="row">
      <div class="p-inputgroup">
      <span class="p-float-label">
        <InputNumber id="min" v-model="goods.lowerLimit"/>
          <label for="min">商品最小下限</label>
        </span>
      </div>
    </div>
    <div class="row">
      <div class="p-inputgroup">
      <span class="p-float-label">
        <InputNumber id="time" v-model="goods.shelfLife"/>
          <label for="time">商品保质期</label>
        </span>
      </div>
    </div>
    <div class="row">
      <div class="p-inputgroup">
      <span class="p-float-label">
        <InputText id="address" v-model="goods.location"/>
          <label for="address">商品产地</label>
        </span>
      </div>
    </div>
    <template #footer>
      <Button class="p-button-text" icon="pi pi-times" label="取消"
              @click="$store.commit('setDialog',{showInfoUpdate:false})"/>
      <Button autofocus icon="pi pi-check" label="确认" @click="updateUser"/>
    </template>
  </Dialog>

  <Dialog :closable="false" :style="{width: '50vw'}" :visible="dialog.showGoodsInput" header="商品入库">
    <div class="row">
      <div class="p-inputgroup">
      <span class="p-float-label">
        <InputNumber id="price" v-model="input.originPrice"/>
          <label for="price">商品价格</label>
        </span>
      </div>
    </div>
    <div class="row">
      <div class="p-inputgroup">
      <span class="p-float-label">
        <InputNumber id="account" v-model="input.count"/>
          <label for="account">入库数量</label>
        </span>
      </div>
    </div>
    <div class="row">
      <Dropdown v-model="input.reviewId" :options="inputOption" optionLabel="name" optionValue="id"
                placeholder="审核表"/>
    </div>
    <template #footer>
      <Button class="p-button-text" icon="pi pi-times" label="取消"
              @click="$store.commit('setDialog',{showGoodsInput:false})"/>
      <Button autofocus icon="pi pi-check" label="确认" @click="toInput"/>
    </template>
  </Dialog>
  <Dialog :closable="false" :style="{width: '50vw'}" :visible="dialog.showGoodsOutput" header="商品出库">
    <div class="row">
      <div class="p-inputgroup">
      <span class="p-float-label">
        <InputNumber id="account" v-model="output.price"/>
          <label for="account">出库价格</label>
        </span>
      </div>
    </div>
    <div class="row">
      <Dropdown v-model="output.reviewId" :options="outPutOption" optionLabel="name" optionValue="id"
                placeholder="审核表"/>
    </div>
    <template #footer>
      <Button class="p-button-text" icon="pi pi-times" label="取消"
              @click="$store.commit('setDialog',{showGoodsOutput:false})"/>
      <Button autofocus icon="pi pi-check" label="确认" @click="toOutput"/>
    </template>
  </Dialog>
  <Dialog :closable="false" :style="{width: '50vw'}" :visible="dialog.showGoodsClear" header="商品清库">
    <div class="row">
      <Dropdown v-model="clear.reviewId" :options="clearOption" optionLabel="name" optionValue="id"
                placeholder="审核表"/>
    </div>
    <template #footer>
      <Button class="p-button-text" icon="pi pi-times" label="取消"
              @click="$store.commit('setDialog',{showGoodsClear:false})"/>
      <Button autofocus icon="pi pi-check" label="确认" @click="toClear"/>
    </template>
  </Dialog>
  <Dialog :closable="false" :style="{width: '50vw'}" :visible="dialog.showGoodsDelete" header="商品删除">
    <div class="row">
      <Dropdown v-model="del.reviewId" :options="deleteOption" optionLabel="name" optionValue="id"
                placeholder="审核表"/>
    </div>
    <template #footer>
      <Button class="p-button-text" icon="pi pi-times" label="取消"
              @click="$store.commit('setDialog',{showGoodsDelete:false})"/>
      <Button autofocus icon="pi pi-check" label="确认" @click="toDelete"/>
    </template>
  </Dialog>
</template>

<script setup>
import vHeader from '@/components/header'

const items = ref([
  {
    label: '商品基本信息',
    icon: 'pi pi-fw pi-plus',
    items: [
      {
        label: '修改商品信息',
        icon: 'pi pi-fw pi-plus',
        command() {
          store.commit('setDialog', {showInfoUpdate: true})
        }
      },
      {
        label: '删除商品信息',
        icon: 'pi pi-fw pi-plus',
        command() {
          toDeleteInfo()
        }
      },
    ],
  }, {
    label: '商品操作',
    icon: 'pi pi-fw pi-plus',
    items: [
      {
        label: '商品入库',
        icon: 'pi pi-fw pi-plus',
        command() {
          store.commit('setDialog', {showGoodsInput: true})
        }
      },
      {
        label: '商品出库',
        icon: 'pi pi-refresh',
        command: () => {
          store.commit('setDialog', {showGoodsOutput: true})
        }
      }, {
        label: '商品清库',
        icon: 'pi pi-times',
        command: () => store.commit('setDialog', {showGoodsClear: true})
      },
      {
        label: '删除商品',
        icon: 'pi pi-times',
        command: () => store.commit('setDialog', {showGoodsDelete: true})
      }
    ]
  }
])

const bread = {
  home: {icon: 'pi pi-home', to: '/index'},
  items: [
    {label: '商品详情', to: '/detail'}
  ]
}

let inputOption = ref([]), outPutOption = ref([]), clearOption = ref([]), deleteOption = ref([])
let input = ref({}), output = ref({}), clear = ref({}), del = ref({})
let detail = ref({}), goods = ref({}), goodsList1 = ref([]), goodsList2 = ref([]), selectGoods = ref([])

import service from '@/request.js'
import S from "@/store"
import {getDays} from "@/util.js"
import {useConfirm} from 'primevue/useconfirm'
import {useToast} from 'primevue/usetoast'
import {computed, onMounted, ref} from 'vue'
import store from '@/store'
import router from '@/router'
import {useRoute} from 'vue-router'

const Toast = useToast(), Confirm = useConfirm()

const route = useRoute()
let dialog = computed(() => store.state.dialog)

const c3 = ref({
  labels: ['正常', '冗余', '过期', '告急'],
  datasets: [{
    data: [0, 0, 0, 0],
    backgroundColor: [
      '#42A5F5',
      '#66BB6A',
      '#FFA726',
      '#db2a94'
    ],
    hoverBackgroundColor: [
      '#64B5F6',
      '#81C784',
      '#FFB74D',
      '#db2a94'
    ]
  }]
})
const c4 = ref({
  labels: getDays(),
  datasets: [{
    label: '近七天商品总数',
    data: [0, 0, 0, 0, 0, 0, 0],
    fill: false,
    borderColor: '#10ca6a'
  }
  ]
})
let _6 = (data) => {
  c4.value.datasets[0].data = data
}
let _1 = ({name, value}) => {
  c3.value.labels = name
  c3.value.datasets[0].data = value
}
Promise.all([ service.get('commodity/graph/status-count'), service.get('commodity/graph/date-commodity-count')]).then(arr=>[_1,_6].forEach((v, j) => v(arr[j])))

function toUpdateInfo() {
  service.put(`commodity/id/${route.query.id}`, goods.value).then(r => {
        detail.value = goods.value
        store.commit('setDialog', {showInfoUpdate: false})
      }
  )
}

function toDeleteInfo() {
  Confirm.require({
    message: '是否删除此商品',
    header: '确认删除',
    icon: 'pi pi-exclamation-triangle',
    accept: () => {
      service.delete(`commodity/id/${route.query.id}`).then(r => {
        router.push('/index')
      }).catch(e => Toast.add({severity: 'error', summary: e, life: 3000}))
    }
  })
}

onMounted(() => {
  //获取审核表
  service.get('review/?isArchive=0').then(result => {
    inputOption.value = result.filter(v => v.type === 0)
    outPutOption.value = result.filter(v => v.type === 1)
    clearOption.value = result.filter(v => v.type === 2)
    deleteOption.value = result.filter(v => v.type === 3)
  })
  //获取商品信息
  service.get('commodity/' + route.query.id).then(r => {
    detail.value = r
    goods.value = r
  })
  getList()
})

function getList() {
  //获取未过期商品
  service.get(`commodity/inTimeCommodityEntityList/id/${route.query.id}`)
      .then(r => {
        S.commit('setLoading', false)
        goodsList1.value = r})
  //获取已过期商品
  service.get(`commodity/loseTimeCommodityEntityList/id/${route.query.id}`)
      .then(r => goodsList2.value = r)
}


function toInput() {
  service.post(`review/id/${input.value.reviewId}/input`, [Object.assign({commodityId: route.query.id}, input.value)])
      .then(r => {
        store.commit('setDialog', {showGoodsInput: false})
        Toast.add({severity: 'success', summary: '操作成功', life: 3000})
        getList()
      }).catch(e => Toast.add({severity: 'error', summary: e, life: 3000}))
}

function toOutput() {
  let arr = []
  if(!selectGoods.value.length) return Toast.add({severity: 'error', summary: '请选择商品条目', life: 3000})
  selectGoods.value.forEach(v => {
    arr.push({
      'commodityEntityId': v,
      'salePrice': output.value.price
    })
  })
  service.post(`review/id/${output.value.reviewId}/output`, arr).then(r => {
    store.commit('setDialog', {showGoodsOutput: false})
    Toast.add({severity: 'success', summary: '操作成功', life: 3000})
    getList()
  }).catch(e => Toast.add({severity: 'error', summary: e, life: 3000}))
}

function toClear() {
  let arr = []
  if(!selectGoods.value.length) return Toast.add({severity: 'error', summary: '请选择商品条目', life: 3000})
  selectGoods.value.forEach(v => {
    arr.push({'commodityEntityId': v,})
  })
  service.post(`review/id/${clear.value.reviewId}/clean`, arr).then(r => {
    store.commit('setDialog', {showGoodsClear: false})
    Toast.add({severity: 'success', summary: '操作成功', life: 3000})
    getList()
  }).catch(e => Toast.add({severity: 'error', summary: e, life: 3000}))
}

function toDelete() {
  let arr = []
  if(!selectGoods.value.length) return Toast.add({severity: 'error', summary: '请选择商品条目', life: 3000})
  selectGoods.value.forEach(v => {
    arr.push({'commodityEntityId': v,})
  })
  service.post(`review/id/${del.value.reviewId}/delete`, arr).then(r => {
    store.commit('setDialog', {showGoodsDelete: false})
    Toast.add({severity: 'success', summary: '操作成功', life: 3000})
    getList()
  }).catch(e => Toast.add({severity: 'error', summary: e, life: 3000}))
}

</script>

<style lang="stylus">
.goods
  padding 10px
  border 1px solid #304562


.row
  margin 30px 40px

.content
  margin 20px

  .inner
    display flex
    justify-content space-between
    margin-top 10px

    img
      width 100px
      height 100px
      border-radius 10px

.desc
  margin-top 20px
</style>
